package com.vital.mshopping;

import java.util.ArrayList;

import com.vital.dao.Bookmark;
import com.vital.dao.Category;
import com.vital.service.DatabaseService;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

/**
 * 	@author btan
 *	@email: btan@tma.com.vn - anbtan@gmail.com
 */
public class BookmarkActivity extends Activity {
	ListView lvBookmark;
	ArrayList<Bookmark> bookmarks;
	BookmarkAdapter adapterBookmark;
	Category category;
	Context mContext;
	int posSelectedItem;
	boolean isOnCreate = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bookmark);
		isOnCreate = true;
		
		lvBookmark = (ListView)findViewById(R.id.lvBookmark);
		mContext = this.getApplicationContext();
		bookmarks = new ArrayList<Bookmark>();
		
		new LoadBookmark().execute();
	}

	private void setAdapterForListBookmark() {
		adapterBookmark = new BookmarkAdapter(getApplicationContext(), R.layout.item_location, bookmarks);
		lvBookmark.setOnItemClickListener(onItemClickListener);
		lvBookmark.setOnItemLongClickListener(onItemLongClickListener);
		lvBookmark.setAdapter(adapterBookmark);
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			showBookmarkDetail(position);
		}
	
	};
	
	private OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {

		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			// TODO Auto-generated method stub
			showOptionMenu(position);
			return true;
		}
	};
	
	/**
	 * show option menu with two options
	 * 1. Edit category
	 * 2. Delete category
	 */
	private void showOptionMenu(int position) {
		posSelectedItem = position;
		AlertDialog.Builder builder = new Builder(BookmarkActivity.this);
		builder.setTitle(R.string.bookmark_dialog_menu_title);
		builder.setItems(R.array.bookmark_dialog_menu_array_choose, new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
					case 0:
						// Delete bookmark
						deleteBookmark(posSelectedItem);
						break;
					case 1:
						// Map view
						showBookmarkOnMap(posSelectedItem);
						break;
					case 2:
						// Detail view
						showBookmarkDetail(posSelectedItem);
						break;
				}
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
	};
	
	private void deleteBookmark(int position) {
		Bookmark bookmark = bookmarks.get(position);
		
		DatabaseService db = new DatabaseService(mContext);
		db.open();
		if (db.removeBookmark(bookmark.getId())) {
			bookmarks.remove(position);
			adapterBookmark.notifyDataSetChanged();
		}
		db.close();
		
	}
	
	private void showBookmarkOnMap(int position) {
		Bookmark bookmark = bookmarks.get(position);
		
		Intent intent = new Intent(getApplicationContext(), MapViewActivity.class);
		intent.putExtra("ObjBookmark", bookmark);
		startActivity(intent);
	}
	
	private void showBookmarkDetail(int position) {
		Bookmark bookmark = bookmarks.get(position);
		
		Intent intent = new Intent(mContext, DetailLocationActivity.class);
		intent.putExtra("ObjBookmark", bookmark);
		startActivity(intent);
		finish();
	}
	
	private void loadBookmarkFromDB() {
		//---create a database service---
		DatabaseService db = new DatabaseService(this);
		
		//---get all bookmark locations from database---
		db.open();
		Cursor c = db.getAllBookmarks();
		if (c.moveToFirst()) {
			do {
				//---set value---
				Bookmark bookmark = new Bookmark();
				bookmark.setLocationId(c.getInt(0));
				bookmark.setLat(c.getFloat(1));
				bookmark.setLng(c.getFloat(2));
				bookmark.setName(c.getString(3));
				bookmark.setPhone(c.getString(4));
				bookmark.setAddress(c.getString(5));
				bookmark.setCategory(c.getInt(6));
				bookmark.setId(c.getInt(7));
				bookmark.setAccuracy(c.getString(8));
				 
				//---add it to category list
				bookmarks.add(bookmark);
			} while (c.moveToNext());
		}
		//---close Cursor and database service---
		c.close();
		db.close();
	}
	
	private class LoadBookmark extends AsyncTask<String, Void, String> {

		private final ProgressDialog progress = new ProgressDialog(BookmarkActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress.setMessage("Loading...");
			progress.show();
		}
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			//---Load Category from database---
	        loadBookmarkFromDB();
			return null;
		}


		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			//---Set adapter for list view category---
	        setAdapterForListBookmark();
			if (progress.isShowing()) {
				progress.dismiss();
			}
			 
		}

		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_bookmark, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
	switch (item.getItemId()) {
		case R.id.bookmark_menu_deleteAll:
			deleteAllBookmark();
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	
	private void deleteAllBookmark() {
		DatabaseService db = new DatabaseService(mContext);
		db.open();
		db.deleteAllBookmark();
		db.close();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isOnCreate) {
			isOnCreate = false;
		} else {
			Intent intent = this.getIntent();
			Bundle b = intent.getExtras();
			if (b.get("removed_bookmarkId") != null) {
				int id = (int)b.getInt("removed_bookmarkId");
				for (int i = 0; i < bookmarks.size(); i++) {
					if (id == bookmarks.get(i).getId()) {
						bookmarks.remove(i);
						break;
					}
				}
				adapterBookmark.notifyDataSetChanged();
			}
			
		}
	}

	
}
